/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */

/*
// 开放的接口
import http from './interface'

http.config.baseUrl = "http://localhost:8080/api/"

http.request(url:'user/list',method:'GET').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list', {status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.post('user', {id:1, status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.put('user/1', {status: 2}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.delete('user/1').then((res)=>{
	console.log(JSON.stringify(res))
}) 

*/
import Config from "../../utils/config"
import store from "../../store/index"

export default {
	config: {
		baseUrl: Config.serverUrl,
		header: {
			'Content-Type': 'application/json;charset=UTF-8',
			// 'Content-Type':'application/x-www-form-urlencoded'
		},
		data: {},
		method: "GET",
		dataType: "json",
		/* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		options.showLoading = options.showLoading
		options.loadingText = options.loadingText || "加载中..."
		options.needCheck = options.needCheck
		options.header = Object.assign({}, options.header || {})

		return new Promise((resolve, reject) => {
			let _config = null
			// options.success = (response) => {
			// 	if(response.statusCode == "401"){
			// 		uni.showModal({
			// 			title: '温馨提示',
			// 			content: '无权访问,请重新登录',
			// 			success: function (res) {
			// 				if (res.confirm) {
			// 					console.log('用户点击确定');
			// 				} else if (res.cancel) {
			// 					console.log('用户点击取消');
			// 				}
			// 			}
			// 		});
			// 	}
			// 	console.log("responseSuccess",response)
			// };
			// options.fail = (response) => {
			// 	uni.showModal({
			// 		title: '温馨提示',
			// 		content: '网络错误,请稍后再试',
			// 		success: function (res) {
			// 			if (res.confirm) {
			// 				console.log('用户点击确定');
			// 			} else if (res.cancel) {
			// 				console.log('用户点击取消');
			// 			}
			// 		}
			// 	});
			// 	console.log("responseFail",response.statusCode)
			// };
			// complete中处理
			options.complete = (response) => {
				uni.hideLoading()
				let statusCode = response.statusCode
				response.config = _config
				
				// _reslog(response) // 统一的请求响应日志记录
				
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}

				if (statusCode === 200) { // 成功
					resolve(response);
				} else if (statusCode === 401) {
					uni.showModal({
						title: '温馨提示',
						content: '无权访问,请重新登录',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								store.commit("updateInfo", {});
								uni.switchTab({
									url: '/pages/center/center'
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
								uni.navigateBack({
								    delta: 1
								});
							}
						}
					});
					return;
				} else {
					uni.showToast({
						title: '网络错误',
						duration: 2000,
						icon: "none"
					});
					reject(response);
				}
			}

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()
			// 是否显示请求loading
			if (_config.showLoading) {
				uni.showLoading({
					title: _config.loadingText,
					mask: true,
				});
			}
			// 是否添加请求token
			const token = store.state.info.token
			if (_config.needCheck && token) {
				_config.header.Authorization = token
			}

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			
			// _reqlog(_config) // 统一的请求日志记录
			const requestTask = uni.request(_config) // uni.request(_config)
			requestTask && store.commit("updateRequestArr", requestTask)
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}
/**
 * 请求接口日志记录
 */
function _reqlog(req) {
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + req.requestId + "】 请求地址：" + req.url)
		if (req.data) {
			console.log("【" + req.requestId + "】 请求参数：" + JSON.stringify(req.data))
		}
	}
	//TODO 调接口异步写入日志数据库
}

/**
 * 响应接口日志记录
 */
function _reslog(res) {
	let _statusCode = res.statusCode;
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + res.config.requestId + "】 请求地址：" + res.config.url)
		if (res.config.data) {
			console.log("【" + res.config.requestId + "】 请求参数：" + JSON.stringify(res.config.data))
		}
		console.log("【" + res.config.requestId + "】 响应结果：" + JSON.stringify(res))
	}
	//TODO 除了接口服务错误外，其他日志调接口异步写入日志数据库
	switch (_statusCode) {
		case 200:
			break;
		case 401:
			break;
		case 404:
			break;
		default:
			break;
	}
}
